<template>
  <div class="main">
    <!-- 数据查询区：表单 -->
    <el-form
      ref="queryRef"
      :model="queryParams"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="预定时间：">
        <el-form-item>
          <div class="block">
            <el-date-picker
              v-model="valueList"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledDate"
              @change="confirmChange"
            />
          </div>
          <!-- <div>
            开始日期: {{ valueList ? valueList[0] : "" }}
            <br />
            结束日期: {{ valueList ? valueList[1] : "" }}
          </div> -->
        </el-form-item>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery(queryRef)">重置</el-button>
      </el-form-item>
    </el-form>
    <hr />
    <br />
    <!-- 数据展示区：卡片 -->
    <!-- <el-row v-loading="loading" :gutter="7" style="margin-left: 5px">
      <el-col
        v-for="room in RoomsDataList"
        :key="room.id"
        :span="4"
        style="margin-bottom: 5px"
      >
        <el-card :style="cardStyle(room)" @click="checkInFrom(room)">
          <template #header>
            <div class="card-header">
              <br />
              <span>{{ room.name }}</span>
            </div>
          </template>
          <div>
            <p>状态: {{ room.status }}</p>
            <br />
            <p>
              价格: <span style="font-size: 20px">{{ room.finalPrice }}¥</span>
            </p>
          </div>
        </el-card>
      </el-col>
    </el-row> -->
    <el-row
      v-for="(room, index) in RoomsDataList"
      :key="index"
      class="room-row"
    >
      <el-col :span="6" class="room-image-col">
        <div class="grid-content ep-bg-purple">
          <!-- 假设图片地址是 room.imageUrl -->
          <img :src="room.image" class="room-image" />
        </div>
      </el-col>
      <el-col :span="18" class="room-info-col">
        <div class="room-info">
          <div class="room-name">{{ room.name }}</div>
          <div class="room-details">
            <div class="room-quantity">
              剩余房间数量: <span class="highlight">{{ room.quantity }}</span>
            </div>
            <div class="room-price">
              价格: <span class="highlight">{{ room.price }}¥</span>
            </div>
            <el-button class="booking-button" @click="bookingFrom(room)"
              >预定</el-button
            >
          </div>
        </div>
      </el-col>
    </el-row>

    <el-dialog v-model="dialogOpen" :title="title" width="350px" append-to-body>
      <el-form
        ref="ruleFormRef"
        style="max-width: 500px"
        :inline="true"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item v-if="false" label="联系人">
          <el-input v-model="ruleForm.roomTypeId" />
        </el-form-item>
        <el-form-item label="预定房型">
          <el-input v-model="roomTypeName" :disabled="true" />
        </el-form-item>
        <el-form-item label="预定时间">
          <el-form-item>
            <el-date-picker
              v-model="ruleForm.startDate"
              disabled
              type="date"
              placeholder="Pick a day"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="ruleForm.leaveDate"
              disabled
              type="date"
              placeholder="Pick a day"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-form-item>

        <el-form-item label="联系人" prop="contact">
          <el-input v-model="ruleForm.contact" placeholder="请输入联系人" />
        </el-form-item>

        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="ruleForm.phone" placeholder="请输入电话号码" />
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >提交</el-button
          >
          <el-button type="info" @click="reset()">重置</el-button>
          <el-button @click="close">关 闭</el-button>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="text-align: center">
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >提交</el-button
          >
          <el-button type="info" @click="reset()">重置</el-button>
          <el-button @click="close">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 数据展示区：分页加载 -->
    <!-- 数据编辑区：新增/修改对话框 默认不显示 -->
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRef, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { listAllRoomTypes } from "@/api/roomtypes";
import type { RoomTypesDTO } from "@/api/rooms";
import {
  getUnBookingRoomTypesQuantity,
  QueryParams,
  BookingForm,
  roomBooking
} from "@/api/roompre";
onMounted(() => {
  // 挂载后加载数据
  init();
  getList();
  getRoomTypesOptions();
});

const queryRef = ref<FormInstance>();
const roomTypesOptions = ref<RoomTypesDTO[]>([]);
const today = new Date();
const contoday = ref(
  today.getFullYear() +
    "-" +
    String(today.getMonth() + 1).padStart(2, "0") +
    "-" +
    String(today.getDate()).padStart(2, "0")
);
let tomorrow = new Date();
let afterTomorrow = new Date(today);
const valueList = ref([]);
function getRoomTypesOptions() {
  listAllRoomTypes().then(response => {
    roomTypesOptions.value = response.data;
  });
}
const query = reactive<QueryParams>({
  startDate: undefined,
  endDate: undefined
});
const queryParams = toRef(query);
// 数据查询区--> 查询按钮
function init() {
  valueList.value[0] = contoday.value;
  tomorrow = new Date(today);
  tomorrow.setDate(today.getDate() + 1);
  afterTomorrow.setDate(today.getDate() + 2);
  valueList.value[0] = tomorrow.toISOString().split("T")[0];
  valueList.value[1] = afterTomorrow.toISOString().split("T")[0];
  queryParams.value.startDate = valueList.value[0];
  queryParams.value.endDate = valueList.value[1];
}
function handleQuery() {
  queryParams.value.startDate = valueList.value[0];
  queryParams.value.endDate = valueList.value[1];
  console.log(queryParams.value);
  getList();
}
function confirmChange() {
  console.log("confirmChange");
  handleQuery();
}

const resetQuery = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  init();
  getList();
};

const loading = ref<boolean>(false); // table数据加载遮罩
const RoomsDataList = ref([]); // table数据

function getList() {
  loading.value = true;
  getUnBookingRoomTypesQuantity(queryParams.value).then(response => {
    RoomsDataList.value = response.data;
    loading.value = false;
  });
  console.log(queryParams.value);
}
const disabledDate = time => {
  // 如果 valueList 中有开始日期，则禁用这个日期之前的所有日期
  // 允许用户选择等于开始日期的那一天
  if (valueList.value.length > 0 && valueList.value[0]) {
    // 允许选择开始日期当天，所以使用 '<=' 来禁用小于等于开始日期的时间
    return time.getTime() < new Date(contoday.value).getTime();
  }
  // 否则不禁用任何日期
  return false;
};
/**
 --------------------------------------------------------------------------
 --------------------------------------------------------------------------
 --------------------------------------------------------------------------
 --------------------------------------------------------------------------
 */
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref<BookingForm>({
  roomTypeId: undefined,
  contact: undefined,
  phone: undefined,
  startDate: undefined,
  leaveDate: undefined
});
// 清空或赋值表单数据
const initForm = () => {
  ruleFormRef.value?.resetFields();
  console.log(ruleForm.value);
};
const rules = reactive<FormRules<BookingForm>>({
  contact: [
    { required: true, message: "联系人姓名不能为空", trigger: "blur" },
    { min: 2, max: 20, message: "姓名长度需在2到20个字符之间", trigger: "blur" }
  ],
  phone: [
    { required: true, message: "电话号码不能为空", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入有效的电话号码",
      trigger: "blur"
    }
  ]
});
const submitForm = async (formEl: FormInstance | undefined) => {
  console.log(ruleForm.value);
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      roomBooking(ruleForm.value).then(response => {
        ElMessage({
          type: "success",
          message: response.msg
        });
        getList();
      });
      dialogOpen.value = false;
    } else {
      ElMessage.error("表单校验失败，请检查输入！");
    }
  });
};
const resetForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
function reset() {
  resetForm(ruleFormRef.value);
  ruleForm.value.contact = undefined;
  ruleForm.value.phone = undefined;
}

const dialogOpen = ref<boolean>(false); //对话框打开
const title = ref<string>("");
const roomTypeName = ref<string>("");

const roomId = ref("");
function bookingFrom(room) {
  initForm();
  roomTypeName.value = room.name;
  ruleForm.value.roomTypeId = room.id;
  ruleForm.value.startDate = valueList.value[0];
  ruleForm.value.leaveDate = valueList.value[1];
  title.value = "正在预定中...";
  dialogOpen.value = true;
}
/** 关闭对话框 */
function close() {
  initForm();
  dialogOpen.value = false;
}
function handleCloseDialog() {
  dialogOpen.value = false;
  // roomTypesId.value = undefined;
  getList();
}
</script>

<style lang="scss" scoped>
.el-card:hover {
  cursor: pointer;
  transition: transform 0.3s;
  transform: scale(1.05);
}

.room-popover {
  padding: 10px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin: 8px 0;
}

.detail-item label {
  min-width: 70px;
  margin-right: 10px;
  color: #666;
}

.detail-item span {
  font-size: 1500;
  font-weight: 500;
  color: #333;
}

.room-row {
  display: flex;
  align-items: stretch; /* 确保子元素高度一致 */
  margin-bottom: 15px;
  overflow: hidden;
  background-color: #f9f9f9; /* 添加浅色背景 */
  border: 1px solid #ccc;
  border-radius: 8px;
}

.room-image-col {
  padding: 10px;
}

.room-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 8px;
}

.room-info-col {
  display: flex;
  flex-direction: column;
  flex-grow: 1; /* 占满剩余空间 */
  justify-content: space-between;
  padding: 20px; /* 增加内边距 */
}

.room-info {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
}

.room-name {
  margin-bottom: 15px;
  font-size: 32px; /* 增大字体大小 */
  font-weight: bold;
}

.room-details {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
}

.room-quantity,
.room-price {
  font-size: 25px; /* 增大字体大小 */
  color: #333;
}

.highlight {
  font-size: 28px; /* 增大字体大小 */
  font-weight: bold;
  color: #ff5722; /* 突出显示的颜色 */
}

.booking-button {
  align-self: flex-end; /* 预定按钮放在最右边 */
  padding: 20px; /* 增加按钮的内边距 */
  margin-top: 10px;
  font-size: 30px; /* 再变大两倍 */
  border-radius: 5px; /* 添加圆角 */
}
</style>
